import cnchar from "../utils/cnchar-all.js"
import delay from "../utils/delay.js";
import { getPuzzlePlan } from "../api/index.js"
export default class StringPuzzle {
    constructor(gameInfo, room) {
        this.gameInfo = gameInfo
        this.room = room
        this.delay = delay
        this.time = 0 // 轮次
        this.args = null,
            this.hasGuessList = null, // 已经彩果的
            this.nextIdioms = null,
            this.tailWord = null
        this.current = ''
        this.timeLeft = 10000
        this.timer = null,
            this.score = {},
            this.startGame = this.startGame
        this.checkGuess = this.checkGuess
        this.stopGame = this.stopGame
        this.sendRules = this.sendRules
        this.mounted()
    }

    mounted() {
        console.log(this.room)
        setTimeout(() => {
            this.startGame()
        }, 1000);
    }
    // 开始游戏时生成秘密数字并开始倒计时  
    async startGame() {
        try {
            console.log('开始')
            const nowPuzzle = cnchar.random.idiom();
            this.current = nowPuzzle[0]
            this.result()
            console.log(this.room)
            console.log(nowPuzzle)
            const res = await this.getExPlan( this.current)
            console.log(res)
            this.delay(100)
            this.room.say('大家一起成语接龙！！只要拼音对得上就可以了哦！\n我先来：' + this.current+'\n'+res)
        } catch (e) {
            console.log(e)
        }
    }
    getExPlan(key){
        key = key || this.current
        return new Promise(async (resolve,roject)=>{
            try{
                const res = await getPuzzlePlan({ key: key  })
                if(res.data){
                    const {pinyin,explanation,derivation,example} = res.data
                    const str = `拼音：${pinyin}\n注释：${explanation}\n出处：${derivation}\n例子：${example}`
                    resolve(str)
                }else{
                    resolve("这个成语解释不出来了^_^ 大家来吧！")
                }
            }catch(e){
                roject(e)
                console.log(e)
            }
        })
    }

    // 检查猜测并给出反馈  
    checkGuess(content, contact) {
        content = content.trim()
        if (/排名|分数|成绩/gi.test(content)) {
            this.getScoreSay(true)
            return
        }
        console.log(this.current)
        console.log(this.nextIdioms)

        console.log(this.nextIdioms.length)
        const last = cnchar.spell(this.tailWord, 'low')
        const first = cnchar.spell(content[0], 'low')
        if (this.nextIdioms.indexOf(content) > -1) {
            // 回答正确
            if (this.checkHas(content)) {
                this.room.say(`${content} 已经猜过了，换一个吧`)
                return false
            }
            this.score[contact.id] = this.score[contact.id] ? this.score[contact.id] + 1 : 1
            this.current = content
            this.result()

            const checkNoRp = (async (content) => {
                this.current = ''
                if (this.checkHas(content)) {
                    content = cnchar._.pickRandomEle(this.nextIdioms)[0]
                    checkNoRp(content)
                } else {
                    this.current = content
                    this.result()
                   const explan= await this.getExPlan( this.current)
                    this.delay(100)
                    this.room.say(this.current+'\n\n'+explan)
                }
            })(cnchar._.pickRandomEle(this.nextIdioms)[0])
            // this.current = cnchar._.pickRandomEle(this.nextIdioms)[0]

        } else if (last !== first) {
            this.delay(100)

            this.room.say`${contact}  挖凑！！大家在玩成语接龙呢，什么是成语接龙？？接龙需要我解释一下吗？？？`
        } else {
            this.delay(100)

            this.room.say`${contact}  你特么在逗我 ${content} 是成语？？\n\n 当前成语:${this.current}`
        }
        // console.log(this.getScoreSay())
    }
    // 判断是否已经才过的成语

    checkHas(content) {
        this.hasGuessList = this.hasGuessList || []
        const hasGuess = this.hasGuessList.some(it => it == content)
        if (!hasGuess) {
            this.hasGuessList.push(content)
        }
        console.log(hasGuess)
        return hasGuess
    }
    result(current) {
        current = current || this.current
        var tailWord = current[current.length - 1];
        this.tailWord = tailWord
        let args = []
        args.push(cnchar.spell(tailWord, 'low'));
        this.args = args
        this.makeNewPuzzle()
    }
    // 生成成语
    makeNewPuzzle(args) {
        args = args || this.args
        let nextIdioms = cnchar.idiom.apply(null, args);
        if (!nextIdioms.length) {
            this.delay(100)

            this.room.say("这个字已经没有成语了！")
            return
        }
        this.nextIdioms = nextIdioms
        // this.current =cnchar._.pickRandomEle(nextIdioms)[0]
    }
    stopGame() {
        clearInterval(this.timer);
        this.nextIdioms = null,
            this.args = null
        this.guesses = 0
        this.timeLeft = 10000
        this.timer = null,
            this.args = null,
            this.tailWord = null
        if (Object.keys(this.score).length) {
            delay(100)
            this.getScoreSay()
        }


    }
    sendRules(contact) {
        this.room.say`${contact} \n\n ${this.gameInfo.rules}`
    }
    async getScoreSay(isGame) {
        // const members = await this.room.memberAll()
        // const scoreKey = Object.keys(this.score)
        // let result = {}
        // scoreKey.map(it => {
        //     const key = (members.find(item => item.id == it)).payload.name
        //     result[key] = this.score[it]
        // })
        // console.log(result)
        // const sortedKeys = Object.keys(result).sort((a, b) => result[b] - result[a]);

        // // 使用排序后的键数组来访问对象的属性  
        // sortedKeys.forEach(key => {
        //     sortedObj[key] = result[key];
        // });
        // let resStr=``
        // Object.keys(sortedObj).map((item,index)=>{
        //     resStr+=` ${index+1}. ${item}: ${sortedObj[item]} \n`
        // })
        // console.log(`猜成语结果排名：\n${resStr}`)
        // members.find(it=>it==)
        const members = await this.room.memberAll();
        const scoreKey = Object.keys(this.score);

        // 使用 reduce 来构建结果对象，并同时进行排序  
        const sortedResult = scoreKey.reduce((result, it) => {
            const member = members.find(item => item.id === it);
            const name = member?.payload.name ?? '未知'; // 使用可选链和空值合并来提供默认值  
            result[name] = (result[name] || 0) + this.score[it]; // 累加分数，避免未定义的键  
            return result;
        }, {});

        // 使用 Object.entries 和 sort 对结果进行排序  
        const sortedEntries = Object.entries(sortedResult).sort(([_, a], [__, b]) => b - a);

        // 构建结果字符串  
        const resStr = sortedEntries.map(([key, value], index) => `${index + 1}. ${key}: ${value} \n`).join('');

        delay(100)
        this.room.say(`猜成语结果排名：\n${resStr}`)
        if (!isGame) {
            delay(100)
            this.score = null
        }

    }
}